package com.unbox.auth.controller;

import com.alibaba.fastjson.JSON;
import com.unbox.admin.entity.UnboxUser;
import com.unbox.admin.fegin.UnBoxUserFegin;
import com.unbox.common.auth.OAuth2User;
import com.unbox.common.response.UnboxResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义获取登录用户信息
 * @author 获取登录用户信息
 */
@RestController
@RequestMapping(value = "/v1")
public class UserController {

    @Autowired
    UnBoxUserFegin userFegin;

    @GetMapping("/user")
    public Principal user(Principal user){
        return user;
    }

    @GetMapping("/userInfo")
    public String me(OAuth2Authentication user) {
        OAuth2User principal = (OAuth2User) user.getPrincipal();
        UnboxUser unboxUser = new UnboxUser();
        unboxUser.setUserName(principal.getUsername());
        UnboxResponse<UnboxUser> unboxUserUnboxResponse = userFegin.info(unboxUser);
        try {
            unboxUserUnboxResponse.checkCodeThrowExcetion();
            unboxUser = unboxUserUnboxResponse.getBody();
            List<String> authoritys = principal.getAuthorities()
                    .stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toList());
            unboxUser.setAuthoritys(authoritys);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(unboxUser);
    }

    @Autowired
    @Qualifier("consumerTokenServices")
    ConsumerTokenServices consumerTokenServices;

    @Autowired
    AuthorizationServerEndpointsConfigurer authorizationServerEndpointsConfigurer;

    @RequestMapping(method = RequestMethod.POST, value = "/oauth/exit")
    public void revokeToken(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String accessToken) throws IOException {
        new SecurityContextLogoutHandler().logout(httpServletRequest, null, null);
        consumerTokenServices.revokeToken(accessToken);
    }
}
